/**
 * Created by zhanglihe on 15/11/10.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'collection',
    'template',
    'model',
    'dialog'
], function ($, common, ready, Collection, template, Model, dialog) {
    var id = getUrlPath(4);
    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            loading();
            this.fetch();
            this.event();

        },
        formData: {},
        fetch: function () {
            var _this = this;
            this.collection = new Collection({
                url: _global.url.api + 'get_goods_copy',
                condition: {id: id, limit: 10, offset: 0},
                model: {
                    url: _global.url.api + 'get_goods_copy/{id}',
                    event: {
                        '.item-edit:click': 'edit',
                        '.item-remove:click': 'remove',
                        '.item-edit-img:click': 'edit_img'
                    },
                    edit_img: function (e) {
                        var item_id = this.data.id;
                        //保存图片
                        var images = [];
                        $.each($('[name="item_' + item_id + '_album"]'), function () {
                            images.push($(this).val());
                        });
                        if (images.length < 1) {
                            Alert({msg: '图片不能为空', type: 'error'});
                            return false;
                        }
                        e.preventDefault();
                        _this.formData.isImg = true;
                        _this.formData.is_share = 1;
                        _this.formData.album = images;
                        new Model({
                            url: _global.url.api + 'get_goods_copy/' + item_id,
                            data: _this.formData,
                            success: function () {
                                Alert({msg: '保存成功'});
                            }
                        }).put();
                    },
                    edit: function (e) {
                        e.preventDefault();
                        var model = this;
                        var tpl = this.data.type == 1 ? 'add-salling-tpl' : 'edit-tpl';
                        dialog({
                            content: template(tpl, this.data),
                            width: 600,
                            title: '编辑文案',
                            ok: function () {
                                model.data.id = model.data.id;
                                model.data.content = model.data.type == 1 ? $('input[name="content"]').val() : $('textarea[name="content"]').val();
                                model.data.listorder = $('[name="listorder"]').val();
                                model.data.is_visible = model.data.type == 1 ? 1 : $('[name="is_visible"]:checked').val();
                                if (!model.put()) {
                                    return false;
                                }
                                _this.collection.fetch();
                            },
                            cancel: function () {
                                _this.dialog = null;
                            }
                        }).show(e.target);
                    },
                    remove: function (e) {
                        e.preventDefault();
                        var model = this;
                        dialog({
                            'content': '确定删除吗?',
                            ok: function () {
                                model.data.goods_id = id;
                                model.del();
                                _this.collection.fetch();
                            }, cancel: function () {
                            }

                        }).show(e.target);
                    }
                },
                callback: function () {
                    this.image();
                    loaded();
                },
                image: function () {
                    $('#album-view').find('li').remove();

                    $('.album-remove').click(function () {
                        $(this).parents('li').remove();
                    });

                    if (this.result.img_list.length < 1) {
                        return true;
                    }
                    $.each(this.result.img_list, function () {
                        var el = $(template('img-tpl', this));
                        _this.album.add(el);
                    });
                }
            });
            this.collection.fetch();
        },

        event: function () {
            var _this = this;

            /**
             * 按状态查询
             */
            $('#btn-status').find('a').on('click', function (e) {
                e.preventDefault();
                _this.collection.condition.status = $(e.target).attr('rel');
                _this.collection.reload();
                $(e.target).addClass('active').siblings().removeClass('active');
            });

            //文案添加
            $('#btn-add').on('click', function (e) {
                e.preventDefault();
                dialog({
                    content: template('add-tpl'),
                    title: '添加分享文案',
                    width: 700,
                    ok: function () {
                        var content = $("textarea[name='content']").val();
                        var listorder = $("input[name='listorder']").val();
                        var is_visible = $("input[name='is_visible']:checked").val();

                        if (!content || !listorder || !is_visible) {
                            Alert({msg: '请完整填写表单', type: 'error'});
                            return false;
                        }

                        new Model({
                            url: _global.url.api + 'get_goods_copy/' + id,
                            data: {content: content, listorder: listorder, is_visible: is_visible},
                        }).post();
                        _this.collection.fetch();
                    },
                    cancel: function () {
                    },
                }).show();
            });

            $('#btn-salling-copy').on('click', function (e) {
                e.preventDefault();
                dialog({
                    content: template('add-salling-tpl'),
                    title: '添加卖点文案',
                    width: 700,
                    ok: function () {
                        var content = $('input[name=content]').val();
                        var listorder = $('input[name=listorder]').val();
                        var type = 1;
                        var is_visible = 1;
                        new Model({
                            url: _global.url.api + 'get_goods_copy/' + id,
                            data: {content: content, listorder: listorder, type: type, is_visible: is_visible},
                        }).post();
                        _this.collection.fetch();
                    }, cancel: function () {
                    },
                }).show();
            })

            //保存图片
            $('#btn-save').on('click', function (e) {
                e.preventDefault();
                _this.formData.isImg = true;
                _this.formData.album = _this.album.get();
                new Model({
                    url: _global.url.api + 'get_goods_copy/' + id,
                    data: _this.formData,
                    success: function () {
                        location.reload()
                    }
                }).put();
            });

            $('body').on('click', '#btn-upload', function (e) {
                e.preventDefault();
                _this.upload_dialog = dialog({
                    content: template('upload-tpl', {}),
                    width: 550,
                    ok: function () {
                        var img = $("#upload-frame")[0].contentWindow.image.get();
                        _this.imgPreview(img);
                    }, cancel: function () {
                    }
                });
                _this.upload_dialog.show();
            });
        },

        //上传图片
        imgPreview: function (img) {
            var _this = this;
            $.each(img, function (n, v) {
                if (typeof v.id !== 'undefined') {
                    _this.album.add($(template('img-tpl', v)));
                }
            });
        },
        album: {
            default: {
                deleted: false,
                init: function () {
                    $('#album-view').append(this.el);
                    this.event();
                },
                event: function () {
                    var _this = this;
                    this.el.on('click', '.album-remove', function (e) {
                        _this.del(e);
                    }).on('click', '.album-default', function (e) {
                        _this.setDefault(e);
                    });
                },
                del: function (e) {
                    var _this = this;
                    e.preventDefault();
                    this.el.remove();
                    $("#upload_show").show();
                    this.deleted = true;
                },
                setDefault: function (e) {
                    e.preventDefault();
                    this.el.addClass('default').siblings().removeClass('default');
                }
            },
            images: [],
            add: function (el) {
                this.images.push($.extend({el: el}, this.default));
                this.images[this.images.length - 1].init();
            },
            get: function () {
                var images = [];
                $.each(this.images, function () {
                    if (!this.deleted) {
                        images.push(this.el.find('[name="album"]').val());
                    }
                });
                return images;
            },
            clear: function () {
                this.images = [];
            }
        }
    };

    new index();

});